const request = require('../../utils/request');
const appKey = require('../../config/appKey');
const common = require('../../utils/common');
class Map {
    /**
     * 设备列表
     * @api {POST}        /map                设备列表
     * @apiName           /map
     * @apiGroup          Map
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": [
             {
                "deviceId": "F52701930DAF67",
                "areaName": "四川省成都市武侯区棕南正街9",
                "isOnline": false,
                "useState": 0,
                "lng": "104.07495",
                "lat": "30.62447"
             }
        ]
       }
     */
    async index(ctx) {
        const { db, Op } = ctx;
        const url =
            'http://xicheba.net/cdyangyang/API/Handler/DevList?apiKey=' +
            appKey.appKey;
        let res = await request.get(url);
        res = JSON.parse(JSON.stringify(res.data));
        // console.log(data);
        for (let i = 0; i < res.length; i++) {
            // 生成二维码
            const src = await common.createCode(res[i].DeviceCode);
            let condition = {
                where: {
                    deviceId: res[i].DeviceCode
                }
            };
            let drives = await db.Drives.findOne(condition);

            if (drives) {
                drives.areaName = res[i].AreaName;
                drives.isOnline = res[i].IsOnline;
                drives.useState = res[i].UseState;
                drives.src = src;
                drives.save();
            }
        }

        let data = await db.Drives.findAll({
            where: {
                merchantId: {
                    [Op.ne]: 0
                }
            },
            attributes: [
                'deviceId',
                'areaName',
                'isOnline',
                'useState',
                'lng',
                'lat'
            ]
        });
        ctx.success(data);
    }
}
module.exports = new Map();
